package com.barbeque.mall.util;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * @author 苏东宇
 * @since 2022/07/16 20:58
 */

public class MD5Utils {


    public static String getMd5(String content) throws NoSuchAlgorithmException {
        //获得消息摘要
        MessageDigest messageDigest = MessageDigest.getInstance("md5");
        byte[] contentBytes = content.getBytes();
        //对字符数组进行摘要
        byte[] resultBytes = messageDigest.digest(contentBytes);
        StringBuffer stringBuffer = new StringBuffer();


        //将结果数组转化为16进制的值
        for (byte resultByte : resultBytes) {
            //temp为16进制的整数
            int temp = resultByte&0xff;
            String s = Integer.toHexString(temp);
            //将0-15(0-f)中的数字前面拼接上一个0
            if (s.length() == 1){
                stringBuffer.append(0);
            }
            stringBuffer.append(s);
        }
        return stringBuffer.toString();
    }


    /**
     * 对md5进行加盐
    * @param content
    * @param salt
     * @return java.lang.String
     * @author 苏东宇
     * @since 2022/07/16 22:01
     */
    public static String getMd5(String content,String salt) throws NoSuchAlgorithmException {
        content = content + "@" + salt + "#";

        return getMd5(content);
    }


    /**
     * 对用户输入的密码和数据库存储的加密密码进行对比，判断密码是否正确
 * @param password
 * @param salt
 * @param md5Password
     * @return boolean
     * @author 苏东宇
     * @since 2022/07/16 22:11
     */
    public static boolean decode(String password, String salt,String md5Password) throws NoSuchAlgorithmException {
        if ((!password.equals(null)) &&(! "".equals(password))){
           return getMd5(password, salt).equals(md5Password);
        }

        return false;
    }

}
